﻿using CKS.Core.Framework;
using CKS.Schedule;
using FreeSql;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Infrastructure;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Core.CronJob
{
    [Schedule]
    public class StatCapacityJob : CronJobBase
    {
        IFreeSql<MesDB> fsql;
        DateTime StatTime = DateTime.Now; //统计日期
        public StatCapacityJob() : base("统计产能", "0/10 * * * * ?")
        {
            fsql = InternalApp.Fsql;
            //查询上次统计的时间
            var lastItem =fsql.Select<CksCapacityreport>().OrderByDescending(a => a.Id).First();
            if(lastItem !=null)
            {
                StatTime = lastItem.StatDate;
            }
            StatTime = StatTime.AddDays(-6);
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            
            while (true)
            {
                var daykey = StatTime.ToString("yyyy-MM-dd");
                var startTime = StatTime.ToString("yyyy-MM-dd 00:00:00").ToDate();
                var endTime = startTime.AddDays(1).AddTicks(-1);
                //统计
              
                var InCount = fsql.Select<CksProductionRecord>()
                    .Where( a=> a.CreatedTime.Between(startTime, endTime) ).Count();
                var output = fsql.Select<CksProductionRecord>()
                    .Where(a => a.CreatedTime.Between(startTime, endTime) && a.ProcessingStatus >11  ).Count();
               

                
                var report = fsql.Select<CksCapacityreport>().Where(a=>a.StatDayKey == daykey).First();
                if (report == null)
                    report = new CksCapacityreport();
                report.StatDayKey = daykey;
                report.StatDate = StatTime;
                report.InputNum = InCount.ToInt();
                report.Output = output.ToInt();
                report.YieldRate = InCount == 0 ? 0 : (output.ToDecimal() / InCount.ToDecimal()).RoundTo4Places();
                if (report.Id == 0)
                    fsql.Insert(report).ExecuteAffrows();
                else
                    fsql.Update<CksCapacityreport>().SetSource(report)
                        .UpdateColumns(a=> new { a.InputNum,a.Output,a.StatDate,a.YieldRate  } ).ExecuteAffrows();


                //日期加1天
                StatTime = StatTime.AddDays(1);
                int StartDay = StatTime.ToString("yyyyMMdd").ToInt();
                int NowDay = DateTime.Now.ToString("yyyyMMdd").ToInt();
                if(StartDay>NowDay)
                {
                    StatTime = StatTime.AddDays(-1);
                    break;
                }
            }
            await Task.CompletedTask;
        }
    }
}
